package com.inspur.jzsxxzx.service.primary;

import com.inspur.jzsxxzx.entity.primary.User;
import com.inspur.jzsxxzx.mapper.primary.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

@Service
public class UserService {
    
    @Autowired
    private UserMapper userMapper;
    
    @Autowired
    private PasswordEncoder passwordEncoder;
    
    public int registerUser(String username, String password) {
        User user = new User(username, passwordEncoder.encode(password));
        return userMapper.insertUser(user);
    }
    
    public User findByUsername(String username) {
        return userMapper.findByUsername(username);
    }
    
    public User findById(Long id) {
        return userMapper.findById(id);
    }

    public boolean updatePassword(Long userId, String oldPassword, String newPassword) {
        User user = userMapper.findById(userId);
        if (user != null && passwordEncoder.matches(oldPassword, user.getPassword())) {
            user.setPassword(passwordEncoder.encode(newPassword));
            // 这里需要在 UserMapper 中添加更新密码的方法
            return userMapper.updatePassword(user) > 0;
        }
        return false;
    }
}